import React, {ChangeEvent, FormEvent, useEffect, useState} from 'react';
import {useHistory} from 'react-router-dom';
import Button from '../common/Button';
import Input from '../common/Input';
import message from '../common/message';
import Spacer from '../common/Spacer';
import {api} from '../utilities/api';

function SignUp() {
  const history = useHistory();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [passwordConfirmation, setPasswordConfirmation] = useState('');

  useEffect(() => {
    document.title = 'SQL开发平台 - 认证';
  }, []);

  const signUp = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const body = {email, password, passwordConfirmation};
    const json = await api.post('/api/signup', body);
    if (json.error) {
      return message.error(json.error);
    }
    history.push('/');
  };

  return (
    <div className='wrapper' style={{
      width: '400px',
      border: '0.1px solid #f1f1f1',
      boxShadow: '0px 0px 3px #a6d4ff',
      textAlign: 'center',
      margin: '100px  auto '
    }}
    >
      <div style={{width: '300px', textAlign: 'center', margin: '50px auto'}}>
        <form onSubmit={signUp}>
          <img src="" style={{width: '250px', textAlign: 'center', margin: '30px auto'}} alt="SQL开发平台"/>
          <Input
            name="email"
            type="email"
            placeholder="账号"
            onChange={(e: ChangeEvent<HTMLInputElement>) =>
              setEmail(e.target.value)
            }
            required
          />
          <Spacer/>
          <Input
            name="password"
            type="password"
            placeholder="密码"
            onChange={(e: ChangeEvent<HTMLInputElement>) =>
              setPassword(e.target.value)
            }
            required
          />
          <Spacer/>
          <Input
            name="passwordConfirmation"
            type="password"
            placeholder="确认密码"
            onChange={(e: ChangeEvent<HTMLInputElement>) =>
              setPasswordConfirmation(e.target.value)
            }
            required
          />
          <Spacer size={2}/>
          <Button style={{width: '100%'}} htmlType="submit" variant="primary">
            认 证
          </Button>
        </form>
      </div>
    </div>

  );
}

export default SignUp;
